define [
	'jquery'
	'helper'
	'template'
	'lib/jquery.couch.js'
], ($, H) ->
	S = {}

	from_YYYY_MM_DD_HH_MM_SS = (d) ->
		d = d.split(' ')[0].split('-')
		nd = new Date()
		nd.setUTCFullYear d[0]
		nd.setUTCMonth Number(d[1]) - 1
		nd.setUTCDate d[2]
		nd

	to_DD_MMM_YY = (d) ->
		d = d.toDateString().split(' ')
		"#{d[2]}-#{d[1]}-#{d[3].slice(2)}"

	$.fn.mb_view_receipt = (SamCtx) ->
		ins = @
		S = SamCtx
		$tpl = $('.tpl', @).hide()

		unless @mb_plugin()
			@mb_plugin 'view_receipt'
			$.subscribe 'mb.donation', (e, arg) ->
				return if arg['for'] isnt 'receipt'
				H.db().openDoc arg['id'],
					success: (donation) ->
						donation = H.objFormat(donation)
						H.db().openDoc donation['donor_id'],
							success: (donor) ->
								donor = H.objFormat donor
								donor.received = donor.org_name or "#{donor.last_name}, #{donor.first_name}"
								donor.province = ", #{donor.province}" if donor.province isnt ""
								donor.donation_type = donation.donation_type
								donor.donation_amount = donation.donation_amount
								donor.donation_date = to_DD_MMM_YY from_YYYY_MM_DD_HH_MM_SS donation.donation_date
								donor._now = to_DD_MMM_YY new Date()

								$('.content', ins).empty().append(S.content $tpl, donor)
								$('td:not(.label)', ins).css('padding-left', '5px')
		return @
	return
